package com.xiumiing.net.base.uitls;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;


import com.blankj.utilcode.util.Utils;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

import timber.log.Timber;

/**
 * @author guguofeng
 * @desc Activity管理类
 * @date 2019/3/12
 * @Copyright: 武汉市追忆那年网络科技有限公司
 */

public class ActivityManager {

    private static Stack<Activity> activityStack = new Stack<>();
    private static ActivityManager instance;
    private String mTag = getClass().getSimpleName();

    private ActivityManager() {
    }

    /**
     * 单一实例
     */
    public static synchronized ActivityManager getAppInstance() {
        if (instance == null) {
            instance = new ActivityManager();
        }
        return instance;
    }

    /**
     * 添加Activity到堆栈
     */
    public synchronized void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<>();
        }
        if (activity != null) {
            activityStack.push(activity);
            Timber.tag(mTag).i("ActivityManager添加了：%s", activity.getClass().getName());
        }
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity currentActivity() {
        if (!activityStack.empty()) {
            return activityStack.peek();
        }
        return null;
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity getActivity(Class cls) {
        if (!activityStack.empty()) {
            for (Activity activity : activityStack) {
                if (TextUtils.equals(cls.getName(), activity.getClass().getName())) {
                   return activity;
                }
            }
        }
        return null;
    }

    /**
     * 移除最后一个Activity
     */
    public void removeActivity(Activity activityRemove) {
        if (activityRemove != null) {
            Iterator<Activity> iterator = activityStack.iterator();
            while (iterator.hasNext()){
                Activity activity = iterator.next();
                if (activityRemove == activity) {
                    iterator.remove();
                }
            }
            Timber.tag(mTag).i("ActivityManager移除了：%s", activityRemove.getClass().getName());
        }
    }


    /**
     * 结束指定类名的Activity
     */
    public synchronized void finishActivity(Class<?> cls) {
        Iterator<Activity> iterator = activityStack.iterator();
        while (iterator.hasNext()){
            Activity activity = iterator.next();
            if (TextUtils.equals(cls.getName(), activity.getClass().getName())) {
                iterator.remove();
                activity.finish();
            }
        }
    }


    /**
     * 结束所有Activity
     */
    public synchronized void finishAllActivity() {
        if (activityStack == null || activityStack.isEmpty()) {
            return;
        }
//        for (Activity activity : activityStack) {
//            activity.finish();
//        }
        activityStack.clear();
    }


    /**
     * 退出应用程序
     */
    @SuppressLint("MissingPermission")
    public void appExit() {
        try {
            finishAllActivity();
            boolean isSucess = killBackgroundProcesses(Utils.getApp());
            Timber.tag(mTag).i(isSucess ? "后台服务进程杀死成功" : "后台服务进程杀死失败");
            System.exit(0);
        } catch (Exception e) {
            Timber.tag(mTag).e(Log.getStackTraceString(e));
        }
    }

    /**
     * 杀死后台服务进程
     *
     * @return {@code true}: 杀死成功<br>{@code false}: 杀死失败
     */
    public static boolean killBackgroundProcesses(@NonNull Context context) {
        String packageName = context.getPackageName();
        android.app.ActivityManager am = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<android.app.ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();
        if (info == null || info.size() == 0) {
            return true;
        }
        for (android.app.ActivityManager.RunningAppProcessInfo aInfo : info) {
            if (Arrays.asList(aInfo.pkgList).contains(packageName)) {
                am.killBackgroundProcesses(packageName);
            }
        }
        info = am.getRunningAppProcesses();
        if (info == null || info.size() == 0) {
            return true;
        }
        for (android.app.ActivityManager.RunningAppProcessInfo aInfo : info) {
            if (Arrays.asList(aInfo.pkgList).contains(packageName)) {
                return false;
            }
        }
        return true;
    }
}
